﻿using Ch9_Portable.Interfaces;
using Ch9_Portable.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Ch9_Portable.ViewModels
{
    public class ItemViewModelBase : INotifyPropertyChanged
    {
        private IDeviceDataService localDataService;
        public ItemViewModelBase()
        {

        }

        public void SetDataService(IDeviceDataService dds)
        {
            localDataService = dds;
        }

        #region Ch9Post (Ch9Item)
        private Ch9Item _ch9Post = null;
        public Ch9Item Ch9Post
        {
            get { return _ch9Post; }
            set
            {
                _ch9Post = value;
                NotifyPropertyChanged("Ch9Post");
            }
        }
        #endregion

        #region IsVideoAvailable (bool)
        private bool _isVideoAvailable = false;
        public bool IsVideoAvailable
        {
            get { return _isVideoAvailable; }
            set
            {
                _isVideoAvailable = value;
                NotifyPropertyChanged("IsVideoAvailable");
            }
        }
        #endregion

        public void SetCh9Item(Ch9Item newItem)
        {
            Ch9Post = newItem;
            // Check to see if there is any video available
            if (newItem.group == null || newItem.group.content == null ||
                newItem.group.content.Count == 0)
                IsVideoAvailable = false;
            else
                IsVideoAvailable = true;
            // STUB: mark as read, save information to file
            SaveReadItem();
        }

        public void SaveReadItem()
        {
            Ch9Post.IsViewed = true;
            if (localDataService.IsRemoteEnabled()) { 
                localDataService.SaveRoamingSession(Ch9Post);
            }
            else
            {
                localDataService.SaveLocalSession(Ch9Post);
            }
        }

        public void SaveViewTime(TimeSpan playerPosition)
        {
            Ch9Post.LatestViewTime = playerPosition;
            if (localDataService.IsRemoteEnabled())
            {
                localDataService.SaveRoamingSession(Ch9Post);
            }
            else
            {
                localDataService.SaveLocalSession(Ch9Post);
            }
        }


        public event PropertyChangedEventHandler PropertyChanged;
        private void NotifyPropertyChanged(String propertyName)
        {
            PropertyChangedEventHandler handler = PropertyChanged;
            if (null != handler)
            {
                handler(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }
}
